package org.wells.dlock.zk.pool;

import java.util.NoSuchElementException;

import org.apache.commons.pool2.ObjectPool;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

public class ZkLock {

	private ObjectPool<CuratorFramework> pool;

	private CuratorFramework client;

	private InterProcessMutex mutex;

	public ZkLock(ObjectPool<CuratorFramework> pool) {
		this.pool = pool;
	}

	/**
	 * 
	 * @param lockName
	 * @throws Exception
	 * @throws IllegalStateException
	 * @throws NoSuchElementException
	 */
	public void lock(String lockName) throws Exception {

		this.client = this.pool.borrowObject();

		// 创建分布式锁, 锁空间的根节点路径为/concurrent/lock
		this.mutex = new InterProcessMutex(client, "/concurrent/lock/" + lockName);
		mutex.acquire();

	}

	public void unlock() {

		try {
			mutex.release();
			
			if (null != client) {
				pool.returnObject(client);
			}
		} catch (Exception e) {
			// ignored
		}
	}
}
